import 'package:flutter/material.dart';

class FutureBuilderDemo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _FutureBuilderDemoState();
  }
}

class _FutureBuilderDemoState extends State<FutureBuilderDemo> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('FutureBuilderDemo'),
        centerTitle: true,
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {});
        },
        child: Icon(Icons.refresh),
      ),
      body: FutureBuilder(
        builder: (context, snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.none:
              return Center(
                child: Text('none(${snapshot.data}) 未设置可执行的future方法'),
              );
            case ConnectionState.waiting:
              return Center(
                child: Text('waiting(${snapshot.data}) 正在执行'),
              );
            case ConnectionState.active:
              return Center(
                child: Text(
                    'active(${snapshot.data}) 有返回数据，但是并没有完成操作。比如StreamBuilder中Stream已传递数据，但是还在等待返回更多数据。再FutureBuilder应该不会出现该情况'),
              );
            case ConnectionState.done:
              return Center(
                child: Text('done(${snapshot.data}) 执行完成'),
              );
            default:
              return Center(
                child: Text('default '),
              );
          }
        },
        //要执行的异步操作，如果为null, 则snapshot.connectionState=ConnectionState.none
        future: _getData(),
        initialData: 'b', // 初始默认返回的数据，之后snapshot会缓存最新得到的数据
      ),
    );
  }

  Future<String> _getData() async {
    await Future.delayed(Duration(seconds: 2));
    return 'a';
  }
}
